import api from './APIConfig.js';
import get from '../request/get'
import post from '../request/post'
import store from '../store/index'
import put from '../request/put/index.js';

let Utils = {
	SysName: "良品至信",
	SysDesc: "",
	ApiUrl: api.AdminWebUrl, //管理端API地址 
	key_user_info_session: "liangpin_user_info_20241004",
	//APKSERVER: "http://140.143.243.125:24542",

	copyObject: (obj) => {
		let json = JSON.parse(JSON.stringify(obj));
		return json;
	},
	navTo(url, param) {

		if (param) {
			url += uni.$u.queryParams(param)
		}
		uni.navigateTo({
			url
		})
	},
	downloadReport(url, searchData) {
		uni.showLoading({
			title: '服务器正在生成报表',
			mask: true
		})
		var token = store.state.userToken;
		uni.request({
			url,
			data: searchData,
			method: 'GET',
			responseType: "arraybuffer",
			header: {
				Authorization: `Bearer ${token}`
			},
			success(res) {
				uni.showLoading({
					title: '报表生成成功',
					mask: true
				})
				console.log(res)
				const contentDisposition = res.header["Content-Disposition"];
				if (contentDisposition) {
					// 正则表达式匹配文件名
					const filenameRegex = /filename="?([^"]+)"?/;

					const match = contentDisposition.match(filenameRegex);
					if (match && match.length > 1) {
						const filename = match[1];
						let ext = filename.split('.')[1];
						console.log("ext =", ext);
						const tmpFileName = wx.env.USER_DATA_PATH + '/' + `订单_${new Date().getTime()}.${ext}`;
						console.log(tmpFileName);
						uni.showLoading({
							title: '正在保存...',
							mask: true
						})
						const fsm = wx.getFileSystemManager();
						fsm.writeFileSync(tmpFileName, res.data, 'binary')
						uni.showLoading({
							title: '正在打开...',
							mask: true
						})
						wx.openDocument({
							filePath: tmpFileName,
							showMenu: true,
							fileType: '.xlsx' | '.xls',
							success(oRes) {
								console.log(oRes)
								uni.hideLoading()
							},
							fail(err) {
								uni.hideLoading()
								console.log(err)
							}
						})

					} else {
						uni.hideLoading()
						console.log('无法解析文件名');
					}
				} else {
					uni.hideLoading()
					console.log('Content-Disposition头不存在');
				}


			},
		})
	},
	goBindCard() {
		var token = store.state.userToken;
		if (token) {
			uni.navigateTo({
				url: '/pages-mine/BindCard/BindCardBefore'
			})
		} else {
			Utils.wxlogin(() => {
				uni.navigateTo({
					url: '/pages-mine/BindCard/BindCardBefore'
				})
			})
		}
	},
	formatSalary(salary) {
		// 判断是否有小数位
		if (salary % 1 === 0) {
			// 如果是整数，直接返回整数部分
			return salary;
		} else {
			// 如果有小数，保留一位小数
			return salary.toFixed(1);
		}
	},

	calculateDistance(lat1, lon1, lat2, lon2) {
		// const R = 6371; // 地球半径，单位：公里  
		// const dLat = Utils.deg2rad(lat2 - lat1); // 纬度差，转换为弧度  
		// const dLon = Utils.deg2rad(lon2 - lon1); // 经度差，转换为弧度  

		// const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		// 	Math.cos(Utils.deg2rad(lat1)) * Math.cos(Utils.deg2rad(lat2)) *
		// 	Math.sin(dLon / 2) * Math.sin(dLon / 2);
		// const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

		// const distance = R * c; // 计算距离  

		//return distance;
		let x = lat2 - lat1;
		let y = lon2 - lon1;
		return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) * 100; //勾股算下直线距离 a²+b²=c² [你学废了吗^_^]
	},
	doOrderAction(id, ac) {
		return new Promise((resolve, reject) => {
			put({
				url: `${Utils.ApiUrl}/orders/${id}?action=${ac}`
			}).then(res => {

				uni.showToast({
					title: '操作成功',
					icon: 'none'
				});
				console.log(res)
				uni.setStorageSync("@orders_liangpin", res)

				if (ac == "CONFIRM_BUYER_PAID" || ac == 'CONFIRM_FIRST_SELLER_PAID') {
					uni.navigateTo({
						url: '/pages-orders/confirmSuccess/confirmSuccess'
					})
				}
				resolve(res);
			}).catch(err => {
				reject(err);
				uni.removeTabBarBadge({
					index: 2
				});
			})
		})
	},
	doAfterOrderAction(id, ac, remark) {
		return new Promise((resolve, reject) => {
			put({
				url: `${Utils.ApiUrl}/afterSales/${id}?action=${ac}&remark=${remark||''}`
			}).then(res => {

				uni.showToast({
					title: '操作成功',
					icon: 'none'
				});
				console.log(res)
				uni.setStorageSync("@orders_after_liangpin", res)

				// 			if (ac == "CONFIRM_BUYER_PAID" || ac == 'CONFIRM_FIRST_SELLER_PAID') {
				// 				uni.navigateTo({
				// 					url: '/pages-orders/confirmSuccess/confirmSuccess'
				// 				})
				// 			}
				resolve(res);
			}).catch(err => {
				reject(err);
				uni.removeTabBarBadge({
					index: 2
				});
			})
		})
	},
	doAfterAction(id, ac) {
		return new Promise((resolve, reject) => {
			put({
				url: `${Utils.ApiUrl}/orders/${id}?action=${ac}`
			}).then(res => {

				uni.showToast({
					title: '操作成功',
					icon: 'none'
				});
				console.log(res)
				uni.setStorageSync("@orders_liangpin", res)
				uni.navigateTo({
					url: '/pages-users/ApplyShop/ApplyShop'
				})
				resolve(res);
			}).catch(err => {
				reject(err);
				uni.removeTabBarBadge({
					index: 2
				});
			})
		})
	},
	uploadFilePromise(path, aRes, dir) {
		let _that = this;
		let ext = path.substring(path.lastIndexOf('.'))
		let _fileKey = `${dir||'images'}/${Utils.guid()}${ext}`;
		return new Promise((resolve, reject) => {


			wx.uploadFile({
				url: aRes.Host, //仅为示例，非真实的接口地址
				filePath: path,
				name: 'file',
				formData: {
					key: _fileKey,
					'Policy': aRes.Policy, //后端Base64编码格式的授权策略 用于签名
					'OSSAccessKeyId': aRes.AccessKeyId, //OSS控制台获取
					'Success_Action_Status': '200', //让服务端返回200,不然，成功上传图片后阿里默认返回statusCode: 204
					'Signature': aRes.Signature, //服务端返回的签名内容 
				},
				success(res) {
					console.log(res)
					if (res.errMsg == 'uploadFile:ok') {
						resolve(`${ aRes.Host}/${_fileKey}`)
					}


				},
				fail(err) {
					console.log(err)
					reject(err)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});

				}
			})
		})

	},
	getUserLevel(level) {
		switch (level) {
			case "AG_CSR":
				return '银顾客';
				break;
			case "AU_CSR":
				return '金顾客';
				break;
			case "AG_SHOP":
				return "银店铺";
				break;
			case "AU_SHOP":
				return "金店铺";
				break;
			case "AG_WHS":
				return "银批发";
				break;
			case "AU_WHS":
				return "金批发";
				break;
			case "AG_AGENT":
				return "银代理";
				break;
			case "AU_AGENT":
				return "金代理";
				break;
			case "MANAGER":
				return "经理";
				break;
			case "AG_DIRECTOR":
				return "总监";
				break;
			case "AU_DIRECTOR":
				return "董事";
				break;
		}
	},
	getAfterStatus(status) {
		switch (status) {
			case 'PENDING':
				return '待审核';
				break;
			case 'APPROVED':
				return '已同意';
				break;
			case 'REJECTED':
				return '已驳回';
				break;
		}
	},
	getOrderStatus(status) {
		switch (status) {
			case "CREATED":
				return '待付款';
				break;
			case "BUYER_PAID":
				return '已付款';
				break;
			case "FIRST_SELLER_PAID":
				return "等待发货";
				break;
			case "SECOND_SELLER_PAID":
				return "等待发货";
				break;
			case "DELIVERING":
				return "已发货";
				break;
			case "RECEIVED":
				return "已完成";
				break;
			case "CANCELLED":
				return "已取消";
				break;

			default:
				return "";
				break;
		}
	},
	getOrderStatus2(status) {
		switch (status) {
			case "CREATED":
				return '等待买家付款';
				break;
			case "BUYER_PAID":
				return '等待经营店辅收款';
				break;
			case "FIRST_SELLER_PAID":
				return "等待管理店辅收款";
				break;
			case "SECOND_SELLER_PAID":
				return "等待平台收款发货";
				break;
			case "DELIVERING":
				return "运输中";
				break;
			case "RECEIVED":
				return "已完成";
				break;
			case "CANCELLED":
				return "已取消";
				break;
	
			default:
				return "";
				break;
		}
	},
	getOrderBtn(action) {
		switch (action) {
			case "CANCEL":
				return '取消订单';
				break;
			case "INFORM_FIRST_SELLER":
				return '提醒收款';
				break;
			case "CONFIRM_BUYER_PAID":
				return "确认收款";
				break;
			case "INFORM_SECOND_SELLER":
				return "提醒收款";
				break;
			case "CONFIRM_FIRST_SELLER_PAID":
				return "确认收款";
				break;
			case "INFORM_HEAD_QUARTER":
				return "申请发货";
				break;
			case "RECEIVE":
				return "确认收货";
				break;
			case "REFUND":
				return "申请售后";
				break;
			default:
				return "";
				break;
		}
	},

	// 辅助函数：将角度转换为弧度  
	deg2rad(deg) {
		return deg * (Math.PI / 180);
	},

	EJobResumeState: {
		Wait: 0, //待审核（初审）
		WaitAgain: 10, //待审核（再审）
		UnPass: 20, //不通过
		Pass: 100, //通过
	},

	ESocietyJobResumeState: {
		Wait: 0, //待审核
		WaitAgain: 10, //待选
		UnPass: 20, //不通过
		Pass: 100, //通过
		InterviePass: 200, //面试通过
		IntervieUnPass: 300 //面试未通过
	},



	copyCode(code) {
		uni.setClipboardData({
			data: code,
			success: function(res) {

				uni.showToast({
					icon: 'none',
					title: '复制成功',
				});
			}
		});
	},

	tryLogin(func) {


		wx.getUserProfile({
			desc: '获取您的昵称、头像、地区及性別', //向用户展示的信息
			//用户点击了登录\

			success: infoRes => {
				console.log(infoRes)

				if (infoRes.errMsg == 'getUserProfile:ok') {
					//开始登录
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {

							get({
								url: `${Utils.ApiUrl}/api/Common/GetWeChatSession`,
								data: {
									code: loginRes.code
								}
							}).then(res => {

								const {
									appId,
									session_key,
									openid
								} = res.Data
								uni.setStorageSync("futian_hr.session_key",
									res.Data);
								uni.setStorageSync("futian_hr.infoRes",
									infoRes);
								post({
									url: `${Utils.ApiUrl}/api/Authentication/MPLoginOrCreate`,
									data: {
										openid: openid,
										name: infoRes.userInfo.nickName,
										// avatar: infoRes.userInfo.avatarUrl,
									}
								}).then((res) => {
									if (res.Result == 1) {
										store.commit("ADD_USER_TOKEN",
											res
											.Data);

										uni.$u.toast("登录成功");
										if (func) {
											func();
										}
									} else {
										uni.$u.toast(res.PromptMessage +
											" " + (res.DebugMessage ||
												''));
										setTimeout(() => {
											uni.switchTab({
												url: '/pages/index/index'
											})
										}, 2000)
									}
								})


							})

						}
					});
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '授权失败' + infoRes.errMsg,
						icon: 'none',
						duration: 2000
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						})
					}, 2000)
				}
			},
			fail: err => {
				console.log(err)
				uni.hideLoading();
				uni.showToast({
					title: '授权失败' + err.errMsg,
					icon: 'none',
					duration: 2000
				});
				// setTimeout(() => {
				// 	uni.switchTab({
				// 		url: '/pages/index/index'
				// 	})
				// }, 2000)
			}
		});
	},
	wxlogin: (func) => {
		uni.showLoading({
			title: "正在登录",
			icon: 'none'
		})
		uni.$u.throttle(Utils.tryLogin(func), 500)
	},

	handleName(name) {
		if (!name) {
			return ""
		}
		let arr = Array.from(name)
		let result = ''
		result = arr[0] + '**'
		return result
	},
	handleIdCard(id) {
		if (!id) {
			return ""
		}
		return id.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2");
	},
	handlePhone: (phone) => {
		if (!phone) {
			return ""
		}
		return phone.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2")
	},
	copyPhone(phone) {
		uni.setClipboardData({
			data: phone,
			success() {
				uni.$u.toast("复制成功");
			}
		})
	},

	getTimes(endTime) {
		let arr = endTime.split(/[- :]/); // that.data.gmtDate时间格式为'2018-08-07 10:23:00'
		let nndate = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
		nndate = Date.parse(nndate)

		return nndate - new Date();
	},
	formatDate: (strTime, fmt) => {
		if (!strTime) {
			return ' '
		}

		let tmpDate = null;
		if (strTime instanceof Date) {
			tmpDate = strTime;
		} else if (strTime.constructor == String) {
			tmpDate = new Date(strTime);
			if (tmpDate == 'Invalid Date') {
				strTime = strTime.replace(/T/g, ' '); //去掉T
				strTime = strTime.replace(/-/g, '/');
				strTime = strTime.replace(/\.\d+/, ' '); //去掉毫秒		 
			}
		} else {}
		if (tmpDate) {
			let o = {
				"M+": tmpDate.getMonth() + 1, //月份
				"d+": tmpDate.getDate(), //日
				"H+": tmpDate.getHours(), //小时
				"m+": tmpDate.getMinutes(), //分
				"s+": tmpDate.getSeconds(), //秒
				"q+": Math.floor((tmpDate.getMonth() + 3) / 3), //季度
				"S": tmpDate.getMilliseconds() //毫秒
			};
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (tmpDate.getFullYear() + "").substr(4 -
				RegExp.$1
				.length));
			for (let k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length ==
						1) ?
					(o[
						k]) : (("00" +
						o[k]).substr(("" + o[k]).length)));

			return fmt;
		} else {
			return "";
		}
	},

	guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},
	SubscribeMessage(templateIds, callbacks) {

		wx.requestSubscribeMessage({
			tmplIds: [templateIds],
			success(res) {
				console.log(res)
				if (res[templateIds] == 'accept') {
					uni.$u.toast("订阅成功");
				}

				callbacks()
			},
			fail(err) {
				console.log(err)

				callbacks()
			}
		})
	},
	dataURLtoBlob(dataurl) {
		var arr = dataurl.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], {
			type: mime
		});
	},
	dataURLtoFile(dataurl, filename) {

		var arr = dataurl.split(','),
			mime = arr[0].match(/:(.*?);/)[1],
			bstr = atob(arr[1]),
			n = bstr.length,
			u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		let file = new File([u8arr], filename, {
			type: mime
		});
		return file;
	},
	getExt(dataurl) {
		this.imgCode = dataurl;
		var arr = dataurl.split(',');
		var mime = arr[0].match(/:(.*?);/)[1];

		return mime.split('/')[1];
	},

}


export default Utils